/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 权限检查页面 - 应用启动时检查和请求必要权限
 */

import 'package:flutter/material.dart';
import '../services/permission_manager.dart';
import '../widgets/common/permission_guide_widget.dart';

/// 权限检查页面
class PermissionCheckPage extends StatefulWidget {
  final VoidCallback? onPermissionGranted;
  final VoidCallback? onSkip;

  const PermissionCheckPage({
    super.key,
    this.onPermissionGranted,
    this.onSkip,
  });

  @override
  State<PermissionCheckPage> createState() => _PermissionCheckPageState();
}

class _PermissionCheckPageState extends State<PermissionCheckPage> {
  bool _isChecking = true;
  PermissionCheckResult? _checkResult;

  @override
  void initState() {
    super.initState();
    _initializePermissions();
  }

  /// 初始化权限检查
  Future<void> _initializePermissions() async {
    try {
      setState(() {
        _isChecking = true;
      });

      // 初始化权限检查
      final result = await PermissionManager.instance.initializePermissions();

      if (mounted) {
        setState(() {
          _checkResult = result;
          _isChecking = false;
        });

        // 如果所有权限都已授予，自动跳转
        if (result.hasAllPermissions) {
          _handlePermissionGranted();
        }
      }
    } catch (error) {
      debugPrint('PermissionCheckPage: 初始化权限检查失败 - $error');
      if (mounted) {
        setState(() {
          _isChecking = false;
        });
      }
    }
  }

  /// 处理权限授予成功
  void _handlePermissionGranted() {
    if (!mounted) return;
    // 延迟执行导航，确保当前操作完成
    Future.delayed(const Duration(milliseconds: 200), () {
      if (mounted) {
        widget.onPermissionGranted?.call();
      }
    });
  }

  /// 处理权限被拒绝
  void _handlePermissionDenied() {
    if (!mounted) return;
    // 延迟执行导航，确保当前操作完成
    Future.delayed(const Duration(milliseconds: 200), () {
      if (mounted) {
        // 可以选择跳过或者继续使用受限功能
        widget.onSkip?.call();
      }
    });
  }

  /// 重新检查权限
  Future<void> _recheckPermissions() async {
    await _initializePermissions();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.surface,
      body: SafeArea(
        child: _buildBody(),
      ),
    );
  }

  Widget _buildBody() {
    if (_isChecking) {
      return _buildLoadingView();
    }

    if (_checkResult?.hasError == true) {
      return _buildErrorView();
    }

    if (_checkResult?.hasAllPermissions == true) {
      return _buildSuccessView();
    }

    return _buildPermissionGuideView();
  }

  /// 构建加载视图
  Widget _buildLoadingView() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('正在检查权限...'),
        ],
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            const Text(
              '权限检查失败',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _checkResult?.error ?? '未知错误',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 24),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: _handlePermissionDenied,
                    child: const Text('跳过'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _recheckPermissions,
                    child: const Text('重试'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建成功视图
  Widget _buildSuccessView() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.check_circle,
              size: 64,
              color: Colors.green,
            ),
            const SizedBox(height: 16),
            const Text(
              '权限检查通过',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '所有必要权限已授予，可以正常使用音频功能',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 24),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _handlePermissionGranted,
                child: const Text('开始使用'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建权限引导视图
  Widget _buildPermissionGuideView() {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 应用图标和标题
            const SizedBox(height: 40),
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Icon(
                Icons.music_note,
                size: 40,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              '音乐播放器',
              style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            const SizedBox(height: 8),
            Text(
              '为了提供最佳的音乐播放体验，我们需要获取一些权限',
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[600],
                  ),
            ),

            const SizedBox(height: 32),

            // 权限引导组件
            PermissionGuideWidget(
              title: '需要的权限',
              description: '以下权限将帮助应用为您提供完整的音乐播放功能：',
              permissions: PermissionItems.audioPlaybackPermissions,
              onPermissionGranted: _handlePermissionGranted,
              onPermissionDenied: _handlePermissionDenied,
              showCloseButton: false,
            ),

            const SizedBox(height: 16),

            // 添加"直接进入应用"按钮，确保用户总能进入应用
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey.withOpacity(0.3)),
              ),
              child: Column(
                children: [
                  Text(
                    '无需权限也可使用',
                    style: TextStyle(
                      fontWeight: FontWeight.w500,
                      color: Colors.grey[700],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '您可以直接进入应用使用基础功能，稍后在需要时再授予权限',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 12),
                  SizedBox(
                    width: double.infinity,
                    child: OutlinedButton(
                      onPressed: _handlePermissionDenied,
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.grey[700],
                        side: BorderSide(color: Colors.grey.withOpacity(0.5)),
                      ),
                      child: const Text('直接进入应用'),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 16),

            // 底部说明
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.info_outline,
                    color: Colors.blue[700],
                    size: 20,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      '我们承诺保护您的隐私，权限仅用于提供音乐播放功能',
                      style: TextStyle(
                        color: Colors.blue[700],
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
